import { request } from '../../request/index.js'
import { showToast, requestPayment } from '../../utils/asyncWx.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabs: [
      {
        id: 0,
        value: "全部",
        isActive: true
      },
      {
        id: 1,
        value: "待支付",
        isActive: false
      },
      {
        id: 2,
        value: "待提货",
        isActive: false
      },
      {
        id: 3,
        value: "已完成",
        isActive: false
      },
      {
        id: 4,
        value: "售后",
        isActive: false
      }
    ],
    //当前被选中的标题的索引
    index: '',
    //传递到订单页面的按钮展示信息
    firstBtnText: {
      pay: '立即支付',
      appointment: '已预约',
      again: '再来一单'
    },
    //传递到订单页面的按钮展示信息
    secondBtnText: '支付尾款',
    //传递到订单页面的页面展示信息
    fruitInfo: {
      orderTime: '下单时间:',
      goodsCount: '数量:',
      totalPrice: '总价:',
      url: '../fruit-order-detail/index?orderStatus='
    },
    orderList: []
  },
  QueryParams: {
    orderState: "",
    pageNum: 1,
    pageSize: 10
  },
  //总页数
  totalPages: 1,
  //立即支付
  async handlePay(e) {
    console.log(e)
    try {
      if (e.detail.info === '立即支付') {
        const orderId = e.detail.orderid
        const orderPaymentMethod = 1
        const token = wx.getStorageSync("token");
        const header = { token }
        const params = { orderPaymentMethod: 1, orderId }
        const res = await request({ url: '/order/fresh/' + orderId + '/payment', method: 'PUT', data: params, header })
        console.log(res)
        const paymentResult = res.data

        const pay = {
          nonceStr: paymentResult.nonceStr,
          package: paymentResult.packageValue,
          paySign: paymentResult.paySign,
          signType: paymentResult.signType,
          timeStamp: paymentResult.timeStamp
        }
        await requestPayment(pay)

        await showToast({ title: '支付成功' })
        wx.navigateTo({
          url: '../fruit-order/index?type=3'
        });
      }
    } catch (error) {
      await showToast({ title: '订单已取消' })
      wx.navigateTo({
        url: '../fruit-order/index?type=1'
      });
      console.log(error)
    }

  },
  //查看详情
  handleDetail() {

  },
  //根据标题索引来激活选中标题数组
  async changeTitleByIndex(index) {
    let { tabs } = this.data
    tabs.forEach((v, i) => i === index ? v.isActive = true : v.isActive = false)
    let i = tabs.findIndex(v => v.isActive === true)
    this.setData({
      tabs,
      index: i
    })
    if (tabs[i].value !== '全部') {
      this.QueryParams.orderState = tabs[i].id
      this.QueryParams.pageNum = 1
      console.log(this.QueryParams)
      // const token = wx.getStorageSync("token");
      // const header = { token }
      // const res = await request({ url: '/order/fresh/personalList', data: this.QueryParams, header })
      // this.setData({
      //   orderList: res.data.data
      // })
      this.getOrders()
    } else {
      this.QueryParams.orderState = ""
      this.getOrders()
    }

  },
  handleTabsItemChange(e) {
    //console.log(e)
    const { index } = e.detail
    this.changeTitleByIndex(index)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const token = wx.getStorageSync("token");
    if (!token) {
      wx.navigateTo({
        url: '../login/index '
      });
      return
    }
    //获取当前小程序的页面栈-内存中的数组  长度 最大是10页面   连续跳转
    //数组中索引最大的页面 就是当前页面
    let pages = getCurrentPages();
    let currentPage = pages[pages.length - 1]
    const { type } = currentPage.options
    //激活选中页面标题
    this.changeTitleByIndex(type - 1)
    //this.getOrders()
  },
  //获取订单列表的方法
  async getOrders() {
    const token = wx.getStorageSync("token");
    const header = { token }
    const res = await request({ url: '/order/fresh/personalList', data: this.QueryParams, header })
    const total = res.data.total
    //计算总页数
    this.totalPages = Math.ceil(total / this.QueryParams.pageSize)
    if (this.QueryParams.pageNum === 1) {
      this.setData({
        orderList: res.data.data
      })
    } else {
      this.setData({
        orderList: [...this.data.orderList, ...res.data.data]
      })
    }
    console.log(res)
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  async onReachBottom() {
    if (this.QueryParams.pageNum >= this.totalPages) {
      await showToast({ title: '没有下一页数据了' })
    } else {
      this.QueryParams.pageNum++
      this.getOrders()
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})